Varying Slopes Models

Hierarchical Models
Regression
Extending mixed-effects models by allowing the relationship (slope) to vary across different groups.

General Principles

To model the relationship between predictor variables and a dependent variable while allowing for varying effects across groups or clusters, we use a varying slopes model.

This approach is useful when we expect the relationship between predictors and the dependent variable to differ across groups (e.g., different slopes for different subjects, locations, or time periods). This allows every unit in the data to have its own unique response to any treatment, exposure, or event, while also improving estimates via pooling.

Considerations

Note
  • We have the same considerations as for Varying intercepts.

  • The idea is pretty similar to categorical models, where a slope is specified for each category. However, here, we also estimate relationships between different groups. This leads to a different mathematical approach, as to model these relationships between groups, we model a matrix of covariance 🛈.

  • To construct the covariance matrix, we use an SRS decomposition where S is a diagonal matrix of standard deviations and R is a correlation matrix. To model the correlation matrix, we use an LKJcorr distribution parametrized with a single control parameter η that controls the amount of regularization. η is usually set to 2 to define a weakly informative prior that is skeptical of extreme correlations near −1 or 1. When we use LKJcorr(1), the prior is flat over all valid correlation matrices. When the value is greater than 1, then extreme correlations are less likely.

  • The standard deviations in S are model with a prior that constrains them to strictly positive values.

Example

Below is an example code snippet demonstrating Bayesian regression with varying effects. This example is based on McElreath (2018).

Simulated data

Code
from BayesForge import bf
import jax.numpy as jnp

# Setup device------------------------------------------------
m = bf(platform="cpu")

# Import Data & Data Manipulation ------------------------------------------------
# Import
data_path = m.load.sim_multivariate_normal(only_path=True)
m.data(data_path, sep=",")
m.data_on_model = dict(
    cafe=jnp.array(m.df.cafe.values, dtype=jnp.int32),
    wait=jnp.array(m.df.wait.values, dtype=jnp.float32),
    N_cafes=len(m.df.cafe.unique()),
    afternoon=jnp.array(m.df.afternoon.values, dtype=jnp.float32),
)


# Define model ------------------------------------------------
def model(cafe, wait, N_cafes, afternoon):
    a = m.dist.normal(5, 2, name="a")
    b = m.dist.normal(-1, 0.5, name="b")
    sigma_cafe = m.dist.exponential(1, shape=(2,), name="sigma_cafe")
    sigma = m.dist.exponential(1, name="sigma")
    Rho = m.dist.lkj(2, 2, name="Rho")
    cov = jnp.outer(sigma_cafe, sigma_cafe) * Rho
    a_cafe_b_cafe = m.dist.multivariate_normal(
        jnp.stack([a, b]), cov, shape=[N_cafes], name="a_b_cafe"
    )

    a_cafe, b_cafe = a_cafe_b_cafe[:, 0], a_cafe_b_cafe[:, 1]
    mu = a_cafe[cafe] + b_cafe[cafe] * afternoon
    m.dist.normal(mu, sigma, obs=wait)


# Run sampler ------------------------------------------------
m.fit(model, progress_bar=False)

# Summary ------------------------------------------------
m.summary()
An NVIDIA GPU may be present on this machine, but a CUDA-enabled jaxlib is not installed. Falling back to cpu.
bf v 0.0.60 package loaded
jax.local_device_count(cpu) = 32
mean sd eti89_lb eti89_ub ess_bulk ess_tail r_hat mcse_mean mcse_sd
Rho[0, 0] 1.00 0.00 1.00 1.00 4000.00 4000.00 NaN 0.00 NaN
Rho[0, 1] -0.55 0.22 -0.84 -0.15 1447.68 1240.32 1.0 0.01 0.0
Rho[1, 0] -0.55 0.22 -0.84 -0.15 1447.68 1240.32 1.0 0.01 0.0
Rho[1, 1] 1.00 0.00 1.00 1.00 4022.06 3956.42 1.0 0.00 0.0
a 3.86 0.26 3.43 4.28 4700.96 3317.59 1.0 0.00 0.0
a_b_cafe[0, 0] 4.23 0.21 3.89 4.57 4531.21 3366.17 1.0 0.00 0.0
a_b_cafe[0, 1] -1.49 0.23 -1.86 -1.13 3318.42 3091.49 1.0 0.00 0.0
a_b_cafe[1, 0] 0.40 0.22 0.05 0.76 2904.26 2335.79 1.0 0.00 0.0
a_b_cafe[1, 1] -0.72 0.29 -1.18 -0.24 1926.52 2118.62 1.0 0.01 0.0
a_b_cafe[2, 0] 4.43 0.21 4.10 4.77 4613.45 3277.91 1.0 0.00 0.0
a_b_cafe[2, 1] -1.39 0.23 -1.78 -1.04 4144.49 3266.40 1.0 0.00 0.0
a_b_cafe[3, 0] 3.65 0.22 3.30 4.00 2649.75 2987.76 1.0 0.00 0.0
a_b_cafe[3, 1] -1.61 0.27 -2.05 -1.22 1886.19 2628.11 1.0 0.01 0.0
a_b_cafe[4, 0] 3.20 0.22 2.84 3.54 2605.67 2772.66 1.0 0.00 0.0
a_b_cafe[4, 1] -1.02 0.25 -1.40 -0.59 1998.95 3044.43 1.0 0.01 0.0
a_b_cafe[5, 0] 3.00 0.21 2.67 3.34 3676.20 2681.76 1.0 0.00 0.0
a_b_cafe[5, 1] -1.40 0.25 -1.81 -1.03 2785.28 2751.89 1.0 0.00 0.0
a_b_cafe[6, 0] 2.87 0.22 2.50 3.23 2709.09 2897.32 1.0 0.00 0.0
a_b_cafe[6, 1] -0.85 0.28 -1.27 -0.37 1379.17 1079.91 1.0 0.01 0.0
a_b_cafe[7, 0] 3.02 0.22 2.69 3.37 3674.60 2891.80 1.0 0.00 0.0
a_b_cafe[7, 1] -1.44 0.25 -1.86 -1.07 2624.31 2861.83 1.0 0.00 0.0
a_b_cafe[8, 0] 5.47 0.21 5.13 5.82 3480.79 3131.87 1.0 0.00 0.0
a_b_cafe[8, 1] -1.48 0.25 -1.87 -1.09 3187.97 3022.77 1.0 0.00 0.0
a_b_cafe[9, 0] 3.45 0.21 3.12 3.79 4014.88 3196.80 1.0 0.00 0.0
a_b_cafe[9, 1] -1.37 0.23 -1.75 -1.01 3711.84 2726.82 1.0 0.00 0.0
a_b_cafe[10, 0] 3.96 0.21 3.62 4.30 3907.35 3130.64 1.0 0.00 0.0
a_b_cafe[10, 1] -1.12 0.25 -1.49 -0.70 2509.79 2735.57 1.0 0.00 0.0
a_b_cafe[11, 0] 4.20 0.21 3.86 4.53 3921.49 3224.05 1.0 0.00 0.0
a_b_cafe[11, 1] -1.30 0.24 -1.67 -0.93 3475.42 3048.89 1.0 0.00 0.0
a_b_cafe[12, 0] 5.38 0.22 5.05 5.73 3620.20 3290.75 1.0 0.00 0.0
a_b_cafe[12, 1] -1.65 0.25 -2.08 -1.26 2726.63 3122.27 1.0 0.00 0.0
a_b_cafe[13, 0] 3.52 0.21 3.18 3.87 3449.83 3146.39 1.0 0.00 0.0
a_b_cafe[13, 1] -1.20 0.23 -1.56 -0.82 2933.41 2556.19 1.0 0.00 0.0
a_b_cafe[14, 0] 3.48 0.21 3.15 3.82 3410.54 2881.56 1.0 0.00 0.0
a_b_cafe[14, 1] -1.14 0.24 -1.50 -0.75 3133.61 3092.29 1.0 0.00 0.0
a_b_cafe[15, 0] 4.30 0.21 3.97 4.64 3991.05 3215.63 1.0 0.00 0.0
a_b_cafe[15, 1] -1.39 0.23 -1.77 -1.04 4073.10 2895.77 1.0 0.00 0.0
a_b_cafe[16, 0] 4.56 0.22 4.22 4.91 3380.27 3032.48 1.0 0.00 0.0
a_b_cafe[16, 1] -1.60 0.24 -2.00 -1.23 2525.99 3137.54 1.0 0.00 0.0
a_b_cafe[17, 0] 4.66 0.21 4.32 4.99 4334.47 3354.24 1.0 0.00 0.0
a_b_cafe[17, 1] -1.34 0.24 -1.71 -0.95 3855.07 3000.99 1.0 0.00 0.0
a_b_cafe[18, 0] 5.42 0.22 5.08 5.77 3235.83 2837.43 1.0 0.00 0.0
a_b_cafe[18, 1] -1.77 0.26 -2.20 -1.36 2073.02 2208.05 1.0 0.01 0.0
a_b_cafe[19, 0] 3.89 0.21 3.55 4.23 3731.68 3044.90 1.0 0.00 0.0
a_b_cafe[19, 1] -1.20 0.23 -1.56 -0.83 2716.22 2872.48 1.0 0.00 0.0
b -1.32 0.11 -1.49 -1.14 2559.98 2800.18 1.0 0.00 0.0
sigma 0.54 0.03 0.49 0.59 4018.33 2869.39 1.0 0.00 0.0
sigma_cafe[0] 1.17 0.19 0.91 1.51 3274.10 2743.67 1.0 0.00 0.0
sigma_cafe[1] 0.36 0.12 0.17 0.55 668.03 666.11 1.0 0.00 0.0
Code
from BayesForge import bf
import jax.numpy as jnp

# Setup device------------------------------------------------
m = bf(platform="cpu")

# Import Data & Data Manipulation ------------------------------------------------

data_path = m.load.sim_multivariate_normal(only_path=True)
m.data(data_path, sep=",")
m.data_on_model = dict(
    cafe=jnp.array(m.df.cafe.values, dtype=jnp.int32),
    wait=jnp.array(m.df.wait.values, dtype=jnp.float32),
    N_cafes=len(m.df.cafe.unique()),
    afternoon=jnp.array(m.df.afternoon.values, dtype=jnp.float32),
)


# Define model ------------------------------------------------
def model(cafe, wait, N_cafes, afternoon):

    sigma = m.dist.exponential(1, name="sigma")

    varying_intercept, varying_slope = m.effects.varying_effects(
        N_vars=1, N_group=N_cafes, group_id=cafe, group_name="cafe", centered=False
    )

    mu = varying_intercept + varying_slope * afternoon
    m.dist.normal(mu, sigma, obs=wait)


# Run sampler ------------------------------------------------
m.fit(model, progress_bar=False)
jax.local_device_count(cpu) = 32
library(BayesForge)
jnp = reticulate::import('jax.numpy')

# Setup platform------------------------------------------------
m=importBF(platform='cpu')

# Import data ------------------------------------------------
data_path = m$load$sim_multivariate_normal(only_path = TRUE)
m$data(data_path, sep = ',')
m$data_on_model <- list(
  cafe = jnp$array(as.integer(m$df$cafe), dtype = jnp$int32),
  wait = jnp$array(as.numeric(m$df$wait), dtype = jnp$float32),
  N_cafes = as.integer(length(unique(m$df$cafe))),
  afternoon = jnp$array(as.numeric(m$df$afternoon), dtype = jnp$float32)
)

# Define model ------------------------------------------------
model <- function(cafe, wait, N_cafes, afternoon){
  sigma = m$dist$exponential(1, name = 'sigma')

  veff = m$effects$varying_effects(
    N_vars = 1L, N_group = N_cafes, group_id = cafe, group_name = 'cafe', centered = FALSE
  )
  varying_intercept = veff[[1]]
  varying_slope = veff[[2]]

  mu = varying_intercept + varying_slope * afternoon

  m$dist$normal(mu, sigma, obs = wait, name = 'wait')
}

# Run MCMC ------------------------------------------------
m$fit(model, progress_bar = FALSE) # Optimize model parameters through MCMC sampling

# Summary ------------------------------------------------
m$summary() # Get posterior distribution
using PyBayesForge

# Setup device------------------------------------------------
m = importBF(platform="cpu")

# Import Data & Data Manipulation ------------------------------------------------
# Import
data_path = m.load.sim_multivariate_normal(only_path = true)

m.data(data_path, sep=',') 
m.data_on_model = pybuiltins.dict(
    cafe = jnp.array(m.df.cafe.values, dtype=jnp.int32),
    wait = jnp.array(m.df.wait.values, dtype=jnp.float32),
    N_cafes = length(m.df.cafe.unique()),    
    afternoon = jnp.array(m.df.afternoon.values, dtype=jnp.float32)
)


# Define model ------------------------------------------------
@BF function model(cafe, wait, N_cafes, afternoon)
    a = m.dist.normal(5, 2,  name = "a")
    b = m.dist.normal(-1, 0.5, name = "b")
    sigma_cafe = m.dist.exponential(1, shape=(2,),  name = "sigma_cafe")
    sigma = m.dist.exponential( 1,  name = "sigma")
    Rho = m.dist.lkj(2, 2, name = "Rho")
    cov = jnp.outer(sigma_cafe, sigma_cafe) * Rho
    a_cafe_b_cafe = m.dist.multivariate_normal(jnp.stack([a, b]), cov, shape = [N_cafes], name = "a_b_cafe")    

    a_cafe, b_cafe = a_cafe_b_cafe[:, 0], a_cafe_b_cafe[:, 1]
    mu = a_cafe[cafe] + b_cafe[cafe] * afternoon
    m.dist.normal(mu, sigma, obs=wait)

end

# Run mcmc ------------------------------------------------
m.fit(model)  # Optimize model parameters through MCMC sampling

# Summary ------------------------------------------------
m.summary() # Get posterior distributions

Mathematical Details

Centered parameterization

The Gaussian Mixture Model is a hierarchical model where each data point is generated from one of K distinct multivariate Gaussian distributions.

The varying intercepts (\alpha_k) and slopes (\beta_k) are modeled using a Multivariate Normal distribution:

\begin{pmatrix} \alpha_k \\ \beta_k \end{pmatrix} \sim \text{MultivariateNormal}\left( \begin{pmatrix} \bar{\alpha} \\ \bar{\beta} \end{pmatrix}, \text{diag}(\varsigma) ~ \Omega ~ \text{diag}(\varsigma) \right)

\bar{\alpha} \sim \text{Normal}(0, 1) \bar{\beta} \sim \text{Normal}(0, 1) \varsigma \sim \text{Exponential}(1) \Omega \sim \text{LKJ}(\eta)

Where:

  • \left(\begin{array}{cc} \bar{\alpha} \\ \bar{\beta} \end{array}\right) is a vector composed from concatenating a parameter for the global intercept and a parameter vector of the global slopes.

  • \varsigma is a vector giving the standard deviation of the random effects for the intercept and slopes across groups.

  • \Omega is the correlation matrix.

Non-centered parameterization

For computational reasons, it is often better to implement a non-centered parameterization 🛈 that is equivalent to the Multivariate Normal distribution approach:

\left(\begin{array}{cc} \alpha_k \\ \beta_k\end{array}\right) = \left(\begin{array}{cc} \bar{\alpha} \\ \bar{\beta} \end{array}\right) + \varsigma\circ \left( L \cdot \left( \begin{array}{cc} \widehat{\alpha}_k \\ \widehat{\beta}_k \end{array} \right) \right)

\bar{\alpha} \sim \text{Normal}(0, 1) \bar{\beta} \sim \text{Normal}(0, 1) \varsigma \sim \text{Exponential}(1) L \sim \text{LKJ Cholesky}(\eta)

\widehat{\alpha}_k \sim \text{Exponential}(1)

\widehat{\beta}_k \sim \text{Exponential}(1)

  • Where:

    • \sigma_\alpha \sim \text{Exponential}(1) is the prior standard deviation among intercepts.

    • \sigma_\beta \sim \text{Exponential}(1) is the prior standard deviation among slopes.

    • L \sim \text{LKJcorr}(\eta) is the a cholesky factor of the correlation matrix matrix using the Cholesky Factor 🛈

Multivariate Model with One Random Slope for Each Variable

We can apply a multivariate model similarly to Chapter 2. In this case, we apply the same principle, but with a covariance matrix with a dimension equal to the number of varying slopes we define. For example, if we want to generate random slopes for i observations in a model with two independent variables X_1 and X_2, we can define the formula as follows:

Y_{i} \sim \text{Normal}(\mu_i , \sigma)

\mu_i = \alpha_i + \beta_{k(i)} X_{1i} + \gamma_{k(i)} X_{2i}


\begin{pmatrix} \alpha\\ \beta\\ \gamma \end{pmatrix} \sim \begin{pmatrix} \bar{\alpha}\\ \bar{\beta}\\ \bar{\gamma} \end{pmatrix} + \varsigma \circ \left( L \cdot \begin{pmatrix} \widehat{\alpha}_{k} \\ \widehat{\beta}_{k} \\ \widehat{\gamma}_{k} \end{pmatrix} \right)

\bar{\alpha} \sim \text{Normal}(0, 1) \bar{\beta} \sim \text{Normal}(0, 1)

\bar{\gamma} \sim \text{Normal}(0, 1)

\varsigma \sim \text{Exponential}(1) L \sim \text{LKJ Cholesky}(2)

\widehat{\alpha}_k \sim \text{Exponential}(1)

\widehat{\beta}_k \sim \text{Exponential}(1)

\widehat{\gamma}_k \sim \text{Exponential}(1)

Model validation tests

Notes

Note
  • We can apply interaction terms similarly to Chapter 3.

  • We can apply categorical variables similarly to Chapter 4.

  • We can apply multiple random effects in BayesForge as follows:

def model(cafe, wait, N_cafes, afternoon, state):
    sigma = m.dist.exponential( 1,  name = 'sigma')
    
    # ⚠️ Note: `alpha_bar` and `beta_bar` are set to zero to ensure the same intercepts for all varying effects. ⚠️
    varying_intercept_1, varying_slope_1 = m.effects.varying_effects(
        N_vars = 1,
        N_group = N_cafes,
        group_id = cafe, 
        group_name='cafe',
        alpha_bar = jnp.array([0]),
        beta_bar = jnp.array([0]),
        centered=True,
    )

    varying_intercept_2, varying_slope_2 = m.effects.varying_effects(
        N_vars = 1,
        N_group = 4,
        group_id = state, 
        group_name='states',
        alpha_bar = jnp.array([0]),
        beta_bar = jnp.array([0]),
        centered=True,
    )

    varying_intercept = varying_intercept_1 + varying_intercept_2
    varying_slope = varying_slope_1 + varying_slope_2

    mu = varying_intercept + varying_slope * afternoon 
    m.dist.normal(mu, sigma, obs=wait)
model <- function(cafe, wait, N_cafes, afternoon, state) {
  sigma <- m$dist$exponential(1, name = "sigma")

  # ⚠️ Note: `alpha_bar` and `beta_bar` are set to zero to ensure the same intercepts for all varying effects. ⚠️
  veff_1 <- m$effects$varying_effects(
    N_vars = 1L,
    N_group = N_cafes,
    group_id = cafe,
    group_name = "cafe",
    alpha_bar = jnp$array(list(0)),
    beta_bar = jnp$array(list(0)),
    centered = TRUE
  )

  veff_2 <- m$effects$varying_effects(
    N_vars = 1L,
    N_group = 4L,
    group_id = state,
    group_name = "states",
    alpha_bar = jnp$array(list(0)),
    beta_bar = jnp$array(list(0)),
    centered = TRUE
  )

  varying_intercept <- veff_1[[1]] + veff_2[[1]]
  varying_slope <- veff_1[[2]] + veff_2[[2]]

  mu <- varying_intercept + varying_slope * afternoon
  m$dist$normal(mu, sigma, obs = wait)
}
@BF function model(cafe, wait, N_cafes, afternoon, state)
    sigma = m.dist.exponential(1, name="sigma")

    # ⚠️ Note: `alpha_bar` and `beta_bar` are set to zero to ensure the same intercepts for all varying effects. ⚠️
    varying_intercept_1, varying_slope_1 = m.effects.varying_effects(
        N_vars=1,
        N_group=N_cafes,
        group_id=cafe,
        group_name="cafe",
        alpha_bar=jnp.array([0]),
        beta_bar=jnp.array([0]),
        centered=true,
    )

    varying_intercept_2, varying_slope_2 = m.effects.varying_effects(
        N_vars=1,
        N_group=4,
        group_id=state,
        group_name="states",
        alpha_bar=jnp.array([0]),
        beta_bar=jnp.array([0]),
        centered=true,
    )

    varying_intercept = varying_intercept_1 + varying_intercept_2
    varying_slope = varying_slope_1 + varying_slope_2

    mu = varying_intercept + varying_slope * afternoon
    m.dist.normal(mu, sigma, obs=wait)
end

Where state is a second varying effect, representing cafes clustered by state.

⚠️ Note: alpha_bar and beta_bar are set to zero to ensure the same intercepts for all varying effects. ⚠️

Reference(s)

McElreath, Richard. 2018. Statistical Rethinking: A Bayesian course with examples in R and Stan. Chapman; Hall/CRC.